package com.handpay.zztong.hp;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.framework.utils.DateUtils;
import com.handpay.zztong.hp.adapter.WithDrawRecordsAdapter;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.WithdrawRecordsBill;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.paymentbill.widget.CalendarDialogView;
import com.handpay.zztong.hp.paymentbill.widget.CalendarView;
import com.handpay.zztong.hp.ui.DialogFactory;
import com.handpay.zztong.hp.ui.ZZTShowDialog;
import com.handpay.zztong.hp.utils.AccountUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;

import se.krka.kahlua.vm.LuaTable;

public class QueryWithdrawRecordsActivity extends ZZTongActivity implements CalendarView.OnItemClickListener {

	private boolean isDatePickerDialog4StartDate = false;
	private ZZTShowDialog<CalendarDialogView> mCalendarDialog;

	// 起始日期控件
	private TextView startDateShowTextView;
	// 结束日期控件
	private TextView endDateShowTextView;


	private QueryWithdrawRecordsActivity context;
	private final String PER_PAGE_RECORD_NUM = "5";
	/**
	 * 查询提现申请记录
	 */
	private ListView WithdrawRecordsListView;
	// 起始日期
	private Date startDate;
	// 结束日期
	private Date endDate;
	private LinearLayout footerView;
	// 页码信息
	private TextView tvPageInfo;
	// 分页按钮
	private Button btnLast, queryButton;
	private Button btnNext;
	private Button btnIndex;
	private Button btnEnd;
	private WithDrawRecordsAdapter queryWithDrawRecordsAdapter;
	private int pageNo = 1;
	// 总金额,总笔数
	private TextView tvWdAmounts, tvRwdAmounts, tvItems;
	private View wdHeadInfo;
	private Double totalPages = -1d;
	// 交易账单列表
	private List<WithdrawRecordsBill> bills;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.wd_query);
		super.onCreate(savedInstanceState);

		initView();
	}

	@Override
	protected boolean isShownTabs() {
		return false;
	}

	public void initView() {
		context = this;
		mCalendarDialog = new ZZTShowDialog<CalendarDialogView>(this, new CalendarDialogView(this), R.style.dialog);
		mCalendarDialog.getContentView().getCalendar().setOnItemClickListener(this);

		WithdrawRecordsListView = (ListView) findViewById(R.id.queryBillsListView);

		LayoutInflater inflater = LayoutInflater.from(this);
		LinearLayout headerView = (LinearLayout) inflater.inflate(R.layout.wd_query_header, null);
		queryButton = (Button) headerView.findViewById(R.id.queryButton);
		queryButton.setOnClickListener(this);
		(headerView.findViewById(R.id.startDateRow)).setOnClickListener(this);
		(headerView.findViewById(R.id.endDateRow)).setOnClickListener(this);

		Date today = DateUtils.formatStringToDate(DateUtils.formatDateToString(new Date(), "yyyyMMdd"), "yyyyMMdd");
		startDateShowTextView = (TextView) headerView.findViewById(R.id.startDateShowTextView);
		endDateShowTextView = (TextView) headerView.findViewById(R.id.endDateShowTextView);
		startDateShowTextView.setText(DateUtils.formatDateToString(today, "yyyy-MM-dd"));
		startDate = today;
		endDateShowTextView.setText(DateUtils.formatDateToString(today, "yyyy-MM-dd"));
		endDate = new Date(today.getTime() + (24 * 60 * 60 * 1000) - 1);
		footerView = (LinearLayout) inflater.inflate(R.layout.layout_more_item, null);
		tvPageInfo = (TextView) footerView.findViewById(R.id.tvPageInfo);
		btnIndex = (Button) this.footerView.findViewById(R.id.btnIndex);
		btnEnd = (Button) this.footerView.findViewById(R.id.btnEnd);
		btnLast = (Button) this.footerView.findViewById(R.id.btnLast);
		btnNext = (Button) this.footerView.findViewById(R.id.btnNext);
		btnIndex.setOnClickListener(this);
		btnEnd.setOnClickListener(this);
		btnLast.setOnClickListener(this);
		btnNext.setOnClickListener(this);

		WithdrawRecordsListView.addHeaderView(headerView);
		WithdrawRecordsListView.addFooterView(footerView);
		WithdrawRecordsListView.setAdapter(queryWithDrawRecordsAdapter);

		tvWdAmounts = (TextView) headerView.findViewById(R.id.tvWdAmounts);
		tvWdAmounts.setText("");
		tvRwdAmounts = (TextView) headerView.findViewById(R.id.tvRwdAmounts);
		tvRwdAmounts.setText("");
		wdHeadInfo = headerView.findViewById(R.id.wd_header_info);
		tvItems = (TextView) headerView.findViewById(R.id.tvItems);
		tvItems.setText("");
		// queryWithDrawRecords(startDate, endDate, pageNo,
		// PER_PAGE_RECORD_NUM);
	}

	@Override
	public ActionBar getActivityActionBar() {
		return new ActionBar(this.getString(R.string.withdraw_records_title), true);
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		int i = v.getId();
		if (i == R.id.startDateRow) {
			this.isDatePickerDialog4StartDate = true;
			mCalendarDialog.getContentView().setCalendarData(startDate);
			mCalendarDialog.show();
		} else if (i == R.id.endDateRow) {
			this.isDatePickerDialog4StartDate = false;
			mCalendarDialog.getContentView().setCalendarData(endDate);
			mCalendarDialog.show();

		} else if (i == R.id.queryButton || i == R.id.btnIndex) {
			pageNo = 1;
			// 查询
			if (DateUtils.isOkDate(this, startDate, endDate) == true) {
				if (DateUtils.changequerystate(startDate, endDate)) {
					// 查询
					queryWithDrawRecords(startDate, endDate, pageNo, PER_PAGE_RECORD_NUM);
				} else {
					this.showAlertDialog(this, getString(R.string.tip), getString(R.string.txselectoutoftime), true, new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
				}
			}

		} else if (i == R.id.btnNext) {
			pageNo++;
			if (DateUtils.isOkDate(this, startDate, endDate) == true) {
				if (DateUtils.changequerystate(startDate, endDate)) {
					// 查询
					queryWithDrawRecords(startDate, endDate, pageNo, PER_PAGE_RECORD_NUM);
				} else {
					this.showAlertDialog(this, getString(R.string.tip), getString(R.string.txselectoutoftime), true, new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
				}
			}
		} else if (i == R.id.btnLast) {
			pageNo--;
			if (isDate() == true) {
				queryWithDrawRecords(startDate, endDate, pageNo, PER_PAGE_RECORD_NUM);
			}

		} else if (i == R.id.btnEnd) {
			pageNo = totalPages.intValue();
			if (isDate() == true) {
				queryWithDrawRecords(startDate, endDate, pageNo, PER_PAGE_RECORD_NUM);
			}

		}
	}

	private boolean isDate() {
		if (this.startDate == null) {
			DialogFactory.showAlertDialog(this, R.string.tip, R.string.select_start_date_tip);
			return false;
		}
		if (this.endDate == null) {
			DialogFactory.showAlertDialog(this, R.string.tip, R.string.select_end_date_tip);
			return false;
		}
		if (startDate.after(endDate)) {
			DialogFactory.showAlertDialog(this, R.string.tip, R.string.select_date_tip);
			return false;
		}
		return true;
	}

	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	// switch (which) {
	// case DialogInterface.BUTTON_POSITIVE:
	// // 编辑输入框，同样可以更新
	// datePicker.clearFocus();
	// Calendar calendar = Calendar.getInstance();
	// calendar.clear();
	// calendar.set(Calendar.YEAR, datePicker.getYear());
	// calendar.set(Calendar.MONTH, datePicker.getMonth());
	// calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
	// if (this.isDatePickerDialog) {
	// this.startDateShowTextView.setText(DateUtils.formatDateToString(calendar.getTime(),
	// "yyyy-MM-dd"));
	// this.startDate = calendar.getTime();
	// Log.i("result", "select---startDate=" + startDate.getTime());
	// Log.i("result", "select---endDate=" + endDate.getTime());
	// Log.i("result", "----------------------------------");
	// } else {
	// this.endDateTextView.setText(DateUtils.formatDateToString(calendar.getTime(),
	// "yyyy-MM-dd"));
	// this.endDate = new Date(calendar.getTimeInMillis() + (24 * 60 * 60 *
	// 1000) - 1);
	// Log.i("result", "select---startDate=" + startDate.getTime());
	// Log.i("result", "select---endDate=" + endDate.getTime());
	// Log.i("result", "----------------------------------");
	// }
	// break;
	// case DialogInterface.BUTTON_NEGATIVE:
	//
	// break;
	// default:
	// break;
	// }
	//
	// }

	public void queryWithDrawRecords(Date queryStartTime, Date queryEndTime, int pageNoString, String pageSizeString) {

		String account = AccountUtils.getAccountName(this);
		String channel = ClientEngine.CHANNEL;

		// 设置请求参数
		// queryRWDRecords.setStartTime(DateUtils.formatDateToString(queryStartTime,
		// "yyyyMMddHHmmss"));
		// queryRWDRecords.setEndTime(DateUtils.formatDateToString(queryEndTime,
		// "yyyyMMddHHmmss"));
		// queryRWDRecords.setaccount(SecureManager.getInstance().des(account,1,
		// null));
		// queryRWDRecords.setpageNo(pageNoString);
		// queryRWDRecords.setpageSize(pageSizeString);
		// queryRWDRecords.setchannel(channel);
		//
		// //开始发送请求
		// queryRWDRecords.doPost();
		Hashtable<String, String> hashtable = new Hashtable<String, String>(6);
		hashtable.put("startTime", DateUtils.formatDateToString(queryStartTime, "yyyyMMddHHmmss"));
		hashtable.put("endTime", DateUtils.formatDateToString(queryEndTime, "yyyyMMddHHmmss"));
		hashtable.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(account, 1, null));
		hashtable.put("pageNo", "" + pageNoString);
		hashtable.put("pageSize", pageSizeString);
		hashtable.put(BaseProtocolKey.CHANNEL, channel);
		doPost(this, "zztNewQueryRWDRecords.do", hashtable);
	}

	// 成功获取数据handler
	private Handler queryBillsSuccessHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			// 通知adapter
			QueryWithdrawRecordsActivity.this.queryWithDrawRecordsAdapter.notifyDataSetChanged();

		}
	};

	@Override
	public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert) {
		if (!super.netResponse(action, resp, true)) {
			if ("zztNewQueryRWDRecords.do".equals(action)) {
				byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData); // 获取到返回的数据
				LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
				// 总笔数
				Double items = (Double) luaTable.rawget("items");
				if (items == null) {
					items = 0d;
				}
				tvItems.setText(Html.fromHtml(getString(R.string.withdraw_records, getResources().getColor(R.color.light_blue), items.intValue())));
				// 总页数
				totalPages = (Double) luaTable.rawget("totalPages");
				Double rwdAmount = (Double) luaTable.rawget("applyAmounts");
				Double wdAmount = (Double) luaTable.rawget("amounts");
				tvRwdAmounts.setText(Html.fromHtml(getString(R.string.withdraw_apply_total, getResources().getColor(R.color.light_blue), rwdAmount / 100)));
				tvWdAmounts.setText(Html.fromHtml(getString(R.string.withdraw_quota_total, getResources().getColor(R.color.light_blue), wdAmount / 100)));
				LuaTable list = (LuaTable) luaTable.rawget("list");
				Vector<LuaTable> dataList = LuaTableUtil.getArray(list);
				if (list != null) {
					bills = new ArrayList<WithdrawRecordsBill>();
					queryWithDrawRecordsAdapter = new WithDrawRecordsAdapter(this, bills);
					WithdrawRecordsListView.setAdapter(queryWithDrawRecordsAdapter);
					for (LuaTable billData : dataList) {
						bills.add(CommonUtils.generateWithdrawRecordsBill(billData));
					}
				}
				if (dataList == null || dataList.size() == 0) {
					DialogFactory.showAlertDialog(this, R.string.tip, R.string.no_wd_data);
					queryWithDrawRecordsAdapter = new WithDrawRecordsAdapter(this, new ArrayList<WithdrawRecordsBill>());
					WithdrawRecordsListView.setAdapter(this.queryWithDrawRecordsAdapter);
					if (pageNo < 2) {
						this.footerView.setVisibility(View.GONE);
					}
					return false;
				}
				tvPageInfo.setText("第" + pageNo + "页" + "  共" + totalPages.intValue() + "页");
				queryBillsSuccessHandler.sendMessage(queryBillsSuccessHandler.obtainMessage());
				this.footerView.setVisibility(View.VISIBLE);
				if (pageNo == 1) {
					btnLast.setEnabled(false);
				} else {
					btnLast.setEnabled(true);
				}
				if (pageNo == totalPages) {
					btnNext.setEnabled(false);
				} else {
					btnNext.setEnabled(true);
				}
			}
		}
		return true;
	}

//	private void upDatePickerTime(Date date) {
//		String sDate = DateUtils.formatDateToString(date, "yyyy-MM-dd");
//		int year = Integer.parseInt(sDate.split("-")[0]);
//		int mm = Integer.parseInt(sDate.split("-")[1]) - 1;
//		int day = Integer.parseInt(sDate.split("-")[2]);
//		HPLog.e("FDL", "year = " + year);
//		HPLog.e("FDL", "getMonth = " + mm);
//		HPLog.e("FDL", "getDate = " + day);
//		datePicker.updateDate(year, mm, day);
//	}

	@Override
	// set yanglun
	public void OnItemClick(Date selectedStartDate, Date selectedEndDate, Date downDate) {
		mCalendarDialog.dismiss();
		if (this.isDatePickerDialog4StartDate) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(downDate);
			this.startDate = calendar.getTime();
			this.startDateShowTextView.setText(DateUtils.formatDateToString(startDate, "yyyy-MM-dd"));
		} else {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(downDate);
			this.endDate = new Date(calendar.getTimeInMillis() + (24 * 60 * 60 * 1000) - 1);
			this.endDateShowTextView.setText(DateUtils.formatDateToString(endDate, "yyyy-MM-dd"));
		}
	}
}
